home *** CD-ROM | disk | FTP | other *** search
/ Technotools / Technotools (Chestnut CD-ROM)(1993).ISO / lang_c / ctutor2 / union2.c < prev    next >
Text File  |  1986-02-07  |  2KB  |  54 lines

  1. #define AUTO 1
  2. #define BOAT 2
  3. #define PLANE 3
  4. #define SHIP 4
  5.  
  6. main()
  7. {
  8. struct automobile {  /* structure for an automobile         */
  9.    int tires;
  10.    int fenders;
  11.    int doors;
  12. };
  13.  
  14. typedef struct {     /* structure for a boat or ship        */
  15.    int displacement;
  16.    char length;
  17. } BOATDEF;
  18.  
  19. struct {
  20.    char vehicle;         /* what type of vehicle?           */
  21.    int weight;           /* gross weight of vehicle         */
  22.    union {               /* type-dependent data             */
  23.       struct automobile car;      /* part 1 of the union    */
  24.       BOATDEF boat;               /* part 2 of the union    */
  25.       struct {
  26.          char engines;
  27.          int wingspan;
  28.       } airplane;                 /* part 3 of the union    */
  29.       BOATDEF ship;               /* part 4 of the union    */
  30.    } vehicle_type;
  31.    int value;            /* value of vehicle in dollars     */
  32.    char owner[32];       /* owners name                     */
  33. } ford, sun_fish, piper_cub;   /* three variable structures */   
  34.  
  35.        /* define a few of the fields as an illustration     */
  36.  
  37.    ford.vehicle = AUTO;
  38.    ford.weight = 2742;              /* with a full gas tank */
  39.    ford.vehicle_type.car.tires = 5;  /* including the spare */
  40.    ford.vehicle_type.car.doors = 2;
  41.  
  42.    sun_fish.value = 3742;           /* trailer not included */
  43.    sun_fish.vehicle_type.boat.length = 20;
  44.  
  45.    piper_cub.vehicle = PLANE;
  46.    piper_cub.vehicle_type.airplane.wingspan = 27;
  47.  
  48.    if (ford.vehicle == AUTO) /* which it is in this case */
  49.       printf("The ford has %d tires.\n",ford.vehicle_type.car.tires);
  50.  
  51.    if (piper_cub.vehicle == AUTO) /* which it is not in this case */
  52.       printf("The plane has %d tires.\n",piper_cub.vehicle_type.
  53.              car.tires);
  54. }